package com.chexiehui.jc.ui.fragment;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.aries.ui.view.radius.RadiusTextView;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.AppApplication;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpLazyLoadFragment;
import com.chexiehui.jc.entity.CarBriefliesInfo;
import com.chexiehui.jc.entity.CarInfo;
import com.chexiehui.jc.entity.CarSeriesInfo;
import com.chexiehui.jc.event.CarCompareRecodeDeleteEvent;
import com.chexiehui.jc.mvp.car.CarSeriesModelListCovenant;
import com.chexiehui.jc.mvp.car.CarSeriesModelListPresenter;
import com.chexiehui.jc.realm.CarInfoDao;
import com.chexiehui.jc.ui.activity.CarModelDetailsActivity;
import com.chexiehui.jc.ui.activity.CarSeriesDetailsActivity;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.NoDoubleClickListener;
import com.chexiehui.jc.utils.NoDoubleClickUtils;
import com.chexiehui.jc.widget.LoadingLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Author: SongJun.
 * CreateDate: 2019/1/21 0021.
 * Description: 车型列表
 */
public class CarSeriesModelListFragment extends BaseMvpLazyLoadFragment<CarSeriesModelListPresenter> implements CarSeriesModelListCovenant.View {

    public static CarSeriesModelListFragment getInstance(CarSeriesInfo seriesInfo, String year) {
        CarSeriesModelListFragment fragment = new CarSeriesModelListFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("seriesInfo", seriesInfo);
        bundle.putString("year", year);
        fragment.setArguments(bundle);
        return fragment;
    }

    @BindView(R.id.recycler)
    RecyclerView mRecycler;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;

    private ArrayList<CarInfo> carModelData;
    private CommonAdapter<CarInfo> carModelAdapter;
    private CarSeriesInfo seriesInfo;
    private String year;

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void beforeSetView() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            seriesInfo = (CarSeriesInfo) bundle.getSerializable("seriesInfo");
            year = bundle.getString("year");
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_car_series_model_list;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        if (seriesInfo == null || StringUtils.isTrimEmpty(year)) {
            loadingLayout.setStatus(LoadingLayout.Empty);
            return;
        }
        loadingLayout.setStatus(LoadingLayout.Loading);
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setEnableOverScrollDrag(false);
        loadingLayout.setOnReloadListener(v -> {
            loadingLayout.setStatus(LoadingLayout.Loading);
            mvpPresenter.getList();
        });
        mRecycler.setLayoutManager(new LinearLayoutManager(mActivity));
        carModelData = new ArrayList<>();
        carModelAdapter = new CommonAdapter<CarInfo>(mActivity, R.layout.item_car_brand_model, carModelData) {
            @Override
            protected void convert(ViewHolder viewHolder, CarInfo item, int position) {
                viewHolder.setText(R.id.tv_item_params, item.getCustomerTitle());
                if (position > 0 && carModelData.get(position - 1).getCustomerTitle().equals(item.getCustomerTitle())) {
                    viewHolder.getView(R.id.tv_item_params).setVisibility(View.GONE);
                } else {
                    viewHolder.getView(R.id.tv_item_params).setVisibility(View.VISIBLE);
                }
                viewHolder.setText(R.id.tv_item_name, item.getShowTitle());
                viewHolder.setText(R.id.tv_item_price, item.getNewPriceStrUnit());
                viewHolder.setText(R.id.tv_item_follow, item.getFollowRateStr());
                viewHolder.setText(R.id.tv_car_price, "车主价：" + item.getNewPriceStrUnit());
                viewHolder.setText(R.id.tv_item_guidance_price, "指导价：" + item.getNewPriceStrUnit());
                viewHolder.getView(R.id.tv_item_inquiry_price).setOnClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        ((CarSeriesDetailsActivity) mActivity).showInquiryPopup(item);
                    }
                });
                RadiusTextView tv_item_model_compare = viewHolder.getView(R.id.tv_item_model_compare);
                CarInfo c = AppApplication.getInstances().getCarInfoDao().queryBuilder()
                        .where(CarInfoDao.Properties.Id.eq(item.getId()))
                        .unique();
                tv_item_model_compare.setSelected(c != null);
                tv_item_model_compare.setOnClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        ((CarSeriesDetailsActivity) mActivity).changeChooseCompareIds(item);
                        carModelAdapter.notifyDataSetChanged();
                    }
                });
            }
        };
        carModelAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (NoDoubleClickUtils.isDoubleClick()) return;
                startActivity(CarModelDetailsActivity.class, new BundleBuilder()
                        .putSerializable("seriesInfo", seriesInfo)
                        .putSerializable("carModel", carModelData.get(position))
                        .create());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        mRecycler.setAdapter(carModelAdapter);
        isPrepared = true;
        lazyLoad();
    }

    @Override
    protected void lazyLoad() {
        if (!isVisible || !isPrepared || mHasLoadedOnce) {
            return;
        }
        loadingLayout.setStatus(LoadingLayout.Loading);
        mvpPresenter.getList();
    }

    @Override
    protected CarSeriesModelListPresenter createPresenter() {
        return new CarSeriesModelListPresenter(this);
    }

    @Override
    public void onGetListSuccess(BaseModel<List<CarBriefliesInfo>> successResult) {
        mHasLoadedOnce = true;
        if (loadingLayout.getStatus() != LoadingLayout.Success) {
            loadingLayout.setStatus(LoadingLayout.Success);
        }
        carModelData.clear();
        for (int i = 0; i < successResult.getData().size(); i++) {
            for (int j = 0; j < successResult.getData().get(i).getCarList().size(); j++) {
                successResult.getData().get(i).getCarList().get(j).setCustomerTitle(successResult.getData().get(i).getTitle());
            }
            carModelData.addAll(successResult.getData().get(i).getCarList());
        }
        carModelAdapter.notifyDataSetChanged();
    }

    @Override
    public void onGetListFailure(BaseModel<Object> failureResult) {
        if (Constants.PAGE_DATA_EMPTY == failureResult.getResultCode()) {
            mHasLoadedOnce = true;
            loadingLayout.setStatus(LoadingLayout.Empty);
            loadingLayout.setEmptyText(failureResult.getResultInfo());
        } else {
            loadingLayout.setStatus(LoadingLayout.Error);
            loadingLayout.setErrorText(failureResult.getResultInfo());
        }
    }

    @Override
    public String getSeriesId() {
        return seriesInfo.getId();
    }

    @Override
    public String getYear() {
        return year;
    }

    @Subscribe
    public void onCarCompareRecodeDeleteEvent(CarCompareRecodeDeleteEvent event) {
        carModelAdapter.notifyDataSetChanged();
    }
}
